﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace System.Collections
{
    public static class BitArrayExtensions
    {
        /// <summary>
        /// <see cref="BitArray"/>转为字节数组
        /// </summary>
        /// <param name="bits"></param>
        /// <returns></returns>
        public static byte[] ToByteArray(this BitArray bits)
        {
            int numBytes = bits.Length / 8;
            if (bits.Length % 8 != 0) numBytes++;
            byte[] bytes = new byte[numBytes];
            int byteIndex = 0, bitIndex = 0;
            for (int i = 0; i < bits.Length; i++)
            {
                if (bits[i])
                    bytes[byteIndex] |= (byte)(1 << (bitIndex));
                bitIndex++;
                if (bitIndex == 8)
                {
                    bitIndex = 0;
                    byteIndex++;
                }
            }
            return bytes;
        }
        /// <summary>
        /// 字节数组转换为<see cref="BitArray"/>
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static BitArray ToBitArray(this byte[] bytes)
        {
            return new BitArray(bytes);
        }
    }
}
